import Lru from 'lru-cache';
import {NetUtil} from "./NetUtil";
import {URL} from "../config/UrlConfig";
import tripleLine from './tripleLine'

let questionCache = new Lru(30);
let clearQuestionCache = function () {
    questionCache = new Lru(30);
};
let getQuestionInfo = function ({id, page, classId}) {


    return new Promise((resolve, reject) => {

        let questions = questionCache.get(`${id}-${page}`);
        console.log(questions);
        if (questions && questions.length !== 0) {

            resolve(questions);
            return;
        }
        console.log('没题目');
        NetUtil.post(URL.schoolBook.getByClassIdAndPageCode, {classId, pageCode: id})
            .then(res => {
                if (res.length == 0) {

                    resolve([]);
                    return;
                }
                let teachingAssistantId = res[0].teachingAssistantId;
                return NetUtil.post(URL.teachingAssistantQuestion.getByAssistantIdAndPage, {
                    teachingAssistantId,
                    currPage: page
                })

            })
            .then(questions => {

                if (!questions) {

                    resolve([]);
                    return;
                }
                if (!questions.assistantCatalogQuestions) {
                    resolve([]);
                    return;
                }
                let resList = [];
                for (let question of questions.assistantCatalogQuestions) {

                    let temp = {
                        teachingAssistantCatalogId: question.teachingAssistantCatalogId,
                        teachingAssistantId: question.teachingAssistantId,
                        teachingAssistantModularId: question.teachingAssistantModularId,
                        questionAnswerArea: question.questionAnswerArea,
                        teachingAssistantCatalogQuestionId: question.id,
                        questionId: question.questionId,
                        questionType: question.questionType
                    };
                    resList.push(temp);
                }
                /** 缓存题目**/
                questionCache.set(`${id}-${page}`, resList);
                resolve(resList);
            })
    })

};
let checkArea = function (page, area, x, y) {
    if (area === {} || area === undefined) {
        return
    }
    let x1 = area.a.x, x2 = area.b.x;
    let y1 = area.a.y, y2 = area.d.y;
    let page1 = area.a.page, page2 = area.d.page;
    return (x > x1 && x < x2) &&
        (
            (page2 > page && page > page1)
            || (page == page1 && y > y1 && ((page == page2 && y < y2)||(page<page2)))
            || (page == page2 && y < y2 && page>page1)
        )
};
const xBias = -0.5, yBias = -2.5;
let getQuestionByPos = function ({id, page, classId, x, y}) {

    return new Promise((resolve, reject) => {
        getQuestionInfo({id, page, classId})
            .then(questions => {
                for (let question of questions) {
                    if (!question['questionAnswerArea']) continue;
                    let area = JSON.parse(question['questionAnswerArea']);
                    let questionAnswerTrack = checkArea(page, area['answerPos'], x + xBias, y + yBias);
                    let selectedBoxIndex = -1;
                    if (questionAnswerTrack === true) {
                        resolve({question, isAnswer: true, selectedBoxIndex})
                    }
                    (area['selectBoxes'] && area['selectBoxes'] !== []) && area['selectBoxes'].forEach((value, index) => {
                        if (checkArea(page, value, x + xBias, y + yBias)) selectedBoxIndex = index;
                    });
                    if (selectedBoxIndex !== -1) {
                        resolve({question, isAnswer: true, selectedBoxIndex})
                    }
                    let questionTrack = checkArea(page, area, x + xBias, y + yBias);
                    // console.log(questionTrack, page, area, x+xBias, y+yBias);
                    if (questionTrack) {
                        if ((area['answerPos'] === {} || !area['answerPos']) && (area['selectBoxes'] === [] || !area['selectBoxes'])) {
                            resolve({question, isAnswer: true, selectedBoxIndex})
                        }
                        resolve({question, isAnswer: false, selectedBoxIndex})
                    }
                }
                resolve({question: {}, isAnswer: false, selectedBoxIndex: -1})
            })
    })
};

let loadStrokeInfo = function (json, jsonStr, classId) {

    return new Promise(async (resolve, reject) => {

        if (json['xy-dot-array']&&json['xy-dot-array'].length === 0) {
            console.error('空白笔画');
            resolve({});
            return;
        }
        if(json.id&&json.id=='0018'){
            console.error('草稿纸');
            resolve({});
            return;
        }
        let dot = json['xy-dot-array'][0];
        let question, isAnswer, selectedBoxIndex;
        try {
            ({question, isAnswer, selectedBoxIndex} = await getQuestionByPos({
                id: json.id,
                classId,
                page: json['code-page'],
                x: dot.x,
                y: dot.y
            }));
            if (!question.questionId) {
                if (json['xy-dot-array'].length <= 2) resolve({});
                dot = json['xy-dot-array'][Math.floor(json['xy-dot-array'].length / 2)];
                ({question, isAnswer, selectedBoxIndex} = await getQuestionByPos({
                    id: json.id,
                    classId,
                    page: json['code-page'],
                    x: dot.x,
                    y: dot.y
                }));
                if (!question.questionId) {
                    dot = json['xy-dot-array'][json['xy-dot-array'].length - 1];
                    ({question, isAnswer, selectedBoxIndex} = await getQuestionByPos({
                        id: json.id,
                        classId,
                        page: json['code-page'],
                        x: dot.x,
                        y: dot.y
                    }));
                    if (!question.questionId) {
                        console.error("  点被舍弃 ", jsonStr);
                        resolve({});
                        return;
                    }
                }
            }
        } catch (e) {
            console.error(json, 'json');
            resolve({});
            return;
        }


        let device = vueMain.$store.getters.getDeviceByMac(json.serialNo)
            , member;
        try {
            member = vueMain.$store.getters.getMemberByDeviceNum(device.deviceNumber);
        } catch (e) {
            console.info('dataMessage', e, device, json.serialNo);
            return
        }
        let temp = {
            studentId: member.memberId,
            teachingAssistantId: question.teachingAssistantId,
            teachingAssistantCatalogId: question.teachingAssistantCatalogId,
            teachingAssistantCatalogQuestionId: question.teachingAssistantCatalogQuestionId,
            questionId: question.questionId,
            classId,
            answerRawData: jsonStr
        };
        // console.log(isAnswer, selectedBoxIndex>-1);
        if ((isAnswer || selectedBoxIndex > -1) && (question.questionType.indexOf('选') !== -1 || question.questionType.indexOf('判') !== -1)
            && tripleLine.checkDotArray(json['xy-dot-array'], member.memberId, question.teachingAssistantCatalogQuestionId, selectedBoxIndex)) {
            console.log(question, selectedBoxIndex, 'canceled');
            let json_temp = Object.assign({}, json);
            json_temp.type = 2;
            if (selectedBoxIndex > -1) json_temp.index = selectedBoxIndex;
            json_temp.endDate = json['stroke-start-time-s'] * 1000 + json['stroke-start-time-ms'];
            temp.answerRawData = JSON.stringify(json_temp);
        }
        resolve(temp);

    })
};

export {getQuestionInfo, getQuestionByPos, loadStrokeInfo, clearQuestionCache}
